/*
	根据生成代码修改
	我的机构人员应用服务
 */
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Abp.UI;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SOEI.Solution.DomainEntities.Organization.DomainService;
using SOEI.Solution.DomainEntities.Organization.Dtos;
using SOEI.Solution.DomainEntities.Parameters.DomainService;
using SOEI.Solution.DomainEntities.Parameters.Dtos;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;

namespace SOEI.Solution.DomainEntities.Organization
{
    /// <summary>
    /// 【扩展模块】  <br/>
    /// 【功能描述】  ：(服务已经过期)我的机构人员，这里公开的服务都是基于当前登陆用户的所属机构<br/>
    /// 【创建日期】  ：2020.05.21 <br/>
    /// 【开发人员】  ：static残影<br/>
    ///</summary>
    [AbpAuthorize()]
    [ApiExplorerSettings(GroupName = "Manager", IgnoreApi = false)]
    public class OursOrganiPersonAppService : SolutionAppServiceBase, IOursOrganiPersonAppService
    {
        /// <summary>
        ///【OrganiPerson】仓储层
        /// </summary>
        private readonly IRepository<OrganiPerson, long> _organipersonRepository;

        /// <summary>
        ///【OrganiPerson】领域服务
        /// </summary>
        private readonly IOrganiPersonManager _organipersonManager;

        /// <summary>
        /// 【Parameter】参数的领域服务
        /// </summary>
        private readonly IParameterManager _parameterManager;


        public OursOrganiPersonAppService(
            IRepository<OrganiPerson, long> organipersonRepository,
            IOrganiPersonManager organipersonManager,
            IParameterManager parameterManager
        )
        {
            _organipersonRepository = organipersonRepository;
            _organipersonManager = organipersonManager;
            _parameterManager = parameterManager;
        }

        #region -------------------------------------------------辅助工具生成---------------------------------------------- 

        /// <summary>
        ///【OrganiPerson】获取的分页列表信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>

        public async Task<PagedResultDto<OrganiPersonListDto>> GetPaged(GetOrganiPersonsInput input)
        {
            //1. 获取当前登录的用户信息（）
            var userEntity = await this.GetCurrentUserAsync();
            //2. 判断当前登录 是否经济机构用户
            if (!userEntity.OrganizeID.HasValue)
            {
                throw new UserFriendlyException("当前登录用户不是经济机构成员！");
            }

            //var query = _organipersonRepository.GetAll()
            var query = this._organipersonManager.QueryUnionEntityListAsNoTracking()
                          //模糊搜索 字段Name
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.Name.Contains(input.FilterText) || a.PhoneNumber.Contains(input.FilterText))
                          .WhereIf(!input.IdNumber.IsNullOrWhiteSpace(), a => a.IDNumber == input.IdNumber)
                          .WhereIf(!input.CertificateCode.IsNullOrWhiteSpace(), a => a.CertificateCode == input.CertificateCode)
                          // 过滤条件只获取我们机构下的数据
                          .Where(x => x.OrganizeID == userEntity.OrganizeID)
            ;

            // TODO:根据传入的参数添加过滤条件
            var count = await query.CountAsync();

            var entityList = await query
                    .OrderBy(input.Sorting).AsNoTracking()
                    .PageBy(input)
                    .ToListAsync();

            var entityListDtos = ObjectMapper.Map<List<OrganiPersonListDto>>(entityList);

            return new PagedResultDto<OrganiPersonListDto>(count, entityListDtos);
        }

        /// <summary>
        ///【OrganiPerson】通过指定id获取MemberListDto信息
        /// </summary>

        public async Task<OrganiPersonListDto> GetById(EntityDto<long> input)
        {
            var entity = await _organipersonRepository.GetAsync(input.Id);

            var dto = ObjectMapper.Map<OrganiPersonListDto>(entity);
            return dto;
        }

        /// <summary>
        ///【OrganiPerson】 获取编辑
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>

        public async Task<GetOrganiPersonForEditOutput> GetForEdit(NullableIdDto<long> input)
        {
            var userEntity = await this.GetPersonChecker();

            var output = new GetOrganiPersonForEditOutput();

            // 编辑时候选择的下拉框人员类型
            var queryPersonType = this._parameterManager.QueryPersonType();
            var personTypeList = await queryPersonType
                                        .AsNoTracking()
                                        .ToListAsync();
            personTypeList = personTypeList.Where(x => !x.Id.Contains("0")).ToList(); // 过滤掉管理员类型
            output.PersonTypes = ObjectMapper.Map<ICollection<ParameterListDto>>(personTypeList);

            OrganiPersonEditDto editDto;

            if (input.Id.HasValue)
            {
                var entity = await _organipersonRepository.GetAsync(input.Id.Value);
                editDto = ObjectMapper.Map<OrganiPersonEditDto>(entity);

            }
            else
            {
                // 新增的人员初始化
                editDto = new OrganiPersonEditDto();
                editDto.OrganizeID = userEntity.OrganizeID.Value;
            }
            output.OrganiPerson = editDto;
            return output;
        }
        /// <summary>
        ///【OrganiPerson】 添加或者修改的公共方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>

        public async Task CreateOrUpdate(CreateOrUpdateOrganiPersonInput input)
        {
            //1. 获取当前登录的用户信息（）
            var userEntity = await this.GetCurrentUserAsync();
            //2. 判断当前登录 是否经济机构用户
            if (!userEntity.OrganizeID.HasValue)
            {
                throw new UserFriendlyException("当前登录用户不是经济机构成员！");
            }

            if (input.OrganiPerson.Id.HasValue)
            {
                await Update(input.OrganiPerson);
            }
            else
            {
                await Create(input.OrganiPerson);
            }
        }
        /// <summary>
        ///【OrganiPerson】新增
        /// </summary>

        protected virtual async Task<OrganiPersonEditDto> Create(OrganiPersonEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增

            // 无论前端传来什么参数都获取当前登录用户的所属机构编号
            var userEntity = await this.GetCurrentUserAsync();
            input.OrganizeID = userEntity.OrganizeID.Value;

            var entity = ObjectMapper.Map<OrganiPerson>(input);
            //调用领域服务
            entity = await _organipersonManager.CreateAsync(entity);

            var dto = ObjectMapper.Map<OrganiPersonEditDto>(entity);
            return dto;
        }

        /// <summary>
        ///【OrganiPerson】编辑
        /// </summary>

        protected virtual async Task Update(OrganiPersonEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新
            // 无论前端传来什么参数都获取当前登录用户的所属机构编号
            var userEntity = await this.GetCurrentUserAsync();
            input.OrganizeID = userEntity.OrganizeID.Value;

            var key = input.Id.Value;
            var entity = await _organipersonRepository.GetAsync(key);
            //  input.MapTo(entity);
            //将input属性的值赋值到entity中
            ObjectMapper.Map(input, entity);
            await _organipersonManager.UpdateAsync(entity);
        }

        /// <summary>
        ///【OrganiPerson】删除信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>

        public async Task Delete(EntityDto<long> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _organipersonManager.DeleteAsync(input.Id);
        }

        /// <summary>
        ///【OrganiPerson】 批量删除Member的方法
        /// </summary>

        public async Task BatchDelete(List<long> input)
        {
            // TODO:批量删除前的逻辑判断，是否允许删除
            await _organipersonManager.BatchDelete(input);
        }

        #endregion

    }
}
